<template>
  <div>
    <el-table
      border
      :data="tableData"
      :key="apiTimes"
    >
      <el-table-column
        prop="installDate"
        label="装柜日期"
        align="center"
        min-width="100"
        fixed="left"
        show-overflow-tooltip
      >
        <template v-slot="{row}">
          {{row.installDate || '-'}}
        </template>
      </el-table-column>
      <el-table-column
        prop="containerName"
        label="货柜名称"
        align="center"
        min-width="100"
        fixed="left"
        show-overflow-tooltip
      >
        <template v-slot="{row}">
          {{row.containerName || '-'}}
        </template>
      </el-table-column>
      <el-table-column
        prop="bookingNum"
        label="订舱号"
        align="center"
        min-width="100"
        fixed="left"
        show-overflow-tooltip
      >
        <template v-slot="{row}">
          {{row.bookingNum || '-'}}
        </template>
      </el-table-column>
      <el-table-column
        prop="containerNo"
        label="货柜/航班号"
        align="center"
        min-width="100"
        fixed="left"
        show-overflow-tooltip
      >
        <template v-slot="{row}">
          {{row.containerNo || '-'}}
        </template>
      </el-table-column>
      <el-table-column
        prop="transferTypeStr"
        label="收货渠道"
        align="center"
        min-width="120"
      ></el-table-column>
      <el-table-column
        prop="startPort"
        label="起始港"
        align="center"
        min-width="100"
      >
        <template v-slot="{row}">
          {{row.startPort || '-'}}
        </template>
      </el-table-column>
      <el-table-column
        prop="targetPort"
        label="目的港"
        align="center"
        min-width="100"
      >
        <template v-slot="{row}">
          {{row.targetPort || '-'}}
        </template>
      </el-table-column>
      <el-table-column
        prop="boxWeight"
        label="箱型重量"
        align="center"
        min-width="100"
      ></el-table-column>
      <el-table-column
        prop="boxNum"
        label="件数"
        align="center"
        min-width="100"
      ></el-table-column>
      <el-table-column
        prop="shipmentNum"
        label="票数"
        align="center"
        min-width="100"
      ></el-table-column>
      <el-table-column
        prop="containerStatusStr"
        label="货柜状态"
        align="center"
        min-width="100"
      ></el-table-column>
      <el-table-column
        prop="weight"
        label="收货实重"
        align="center"
        min-width="100"
      ></el-table-column>
      <el-table-column
        prop="volumeWeight"
        label="收货材积重"
        align="center"
        min-width="100"
      ></el-table-column>
      <el-table-column
        prop="calWeight"
        label="收货计费重"
        align="center"
        min-width="100"
      ></el-table-column>
      <el-table-column
        prop="squareNumber"
        label="方数"
        align="center"
        min-width="100"
      ></el-table-column>
      <el-table-column
        prop="feeValue"
        label="应收合计"
        align="center"
        min-width="100"
      >
        <template v-slot="{row}">
          <template v-if="row.feeValue !== null">
            {{row.feeValue}}
          </template>
          <template v-else>
            -
          </template>
        </template>
      </el-table-column>

      <el-table-column
        v-for="item in agentList"
        :key="item.id"
        :prop="'costValueAgentId' + item.id"
        :label="item.nickname"
        align="center"
        min-width="100"
      >
        <template v-slot="{row}">
          <template v-if="row['costValueAgentId' + item.id] !== undefined">
            {{row['costValueAgentId' + item.id]}}
          </template>
          <template v-else>
            -
          </template>
        </template>
      </el-table-column>
      <el-table-column
        prop="costValue"
        label="成本合计"
        align="center"
        min-width="100"
      ></el-table-column>
      <el-table-column
        prop="gross"
        label="毛利"
        align="center"
        min-width="100"
      ></el-table-column>
      <el-table-column
        prop="grossRate"
        label="利润率%"
        align="center"
        min-width="100"
      ></el-table-column>
      <el-table-column
        prop="createTime"
        label="制单时间"
        align="center"
        min-width="100"
      >
        <template v-slot="{row}">
          {{formatDate(row.createTime, timeFormat)}}
        </template>
      </el-table-column>
      <el-table-column
        prop="costStatusStr"
        label="状态"
        align="center"
        min-width="100"
        fixed="right"
      ></el-table-column>
      <el-table-column
        prop="op"
        label="操作"
        align="left"
        min-width="200"
        fixed="right"
      >
        <template v-slot="{row}">
          <div class="btn-box">
            <template v-if="row.costStatus !== 'untreated'">
              <el-button type="success" @click="showCostDialog(row)">成本分摊</el-button>
            </template>
            <template v-if="row.costStatus === 'untreated'">
              <el-button type="primary" @click="showDialog(row)">导入成本</el-button>
            </template>
            <template v-else-if="row.costStatus === 'wait_settle'">
              <el-button type="warning" @click="showDialog(row)">修改成本</el-button>
            </template>
          </div>

        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      :visible.sync="dialog"
      width="500px"
      :title="dialogForm.feeId ? '修改成本' : '导入成本'"
    >
      <el-form :model="dialogForm" ref="dialogForm">
        <div class="cost-box" v-if="dialogForm.seaCostList.length > 0">
          <div class="cost-title">海运成本</div>
          <div class="cost-item cost-header">
            <div class="cost-label">费用名</div>
            <div class="cost-value">成本（元）</div>
            <div class="cost-agent">代理</div>
          </div>
          <div
            class="cost-item"
            v-for="item in dialogForm.seaCostList"
            :key="item.id"
          >
            <div class="cost-label">{{ item.costName }}</div>
            <div class="cost-value">
              <el-input-number v-model="item.costValue" :min="0" :precision="2"></el-input-number>
            </div>
            <div class="cost-agent">
              <el-select v-model="item.agentId" style="width: 150px">
                <el-option
                  v-for="agent in item.agentList"
                  :key="agent.id"
                  :label="agent.nickname"
                  :value="agent.id"
                ></el-option>
              </el-select>
            </div>
          </div>
        </div>

        <div class="cost-box" v-if="dialogForm.airCostList.length > 0">
          <div class="cost-title">空运成本</div>
          <div class="cost-item cost-header">
            <div class="cost-label">费用名</div>
            <div class="cost-value">成本（元）</div>
            <div class="cost-agent">代理</div>
          </div>
          <div
            class="cost-item"
            v-for="item in dialogForm.airCostList"
            :key="item.id"
          >
            <div class="cost-label">{{ item.costName }}</div>
            <div class="cost-value">
              <el-input-number v-model="item.costValue" :min="0" :precision="2"></el-input-number>
            </div>
            <div class="cost-agent">
              <el-select v-model="item.agentId" style="width: 150px">
                <el-option
                  v-for="agent in item.agentList"
                  :key="agent.id"
                  :label="agent.nickname"
                  :value="agent.id"
                ></el-option>
              </el-select>
            </div>
          </div>
        </div>

        <div class="cost-box mgt20" v-if="dialogForm.HWCCostList.length > 0">
          <div class="cost-title">海外仓成本</div>
          <div class="cost-item cost-header">
            <div class="cost-label">费用名</div>
            <div class="cost-value">成本（元）</div>
            <div class="cost-agent">代理</div>
          </div>
          <div
            class="cost-item"
            v-for="item in dialogForm.HWCCostList"
            :key="item.id"
          >
            <div class="cost-label">{{ item.costName }}</div>
            <div class="cost-value">
              <el-input-number v-model="item.costValue" :min="0" :precision="2"></el-input-number>
            </div>
            <div class="cost-agent">
              <el-select v-model="item.agentId" style="width: 150px">
                <el-option
                  v-for="agent in item.agentList"
                  :key="agent.id"
                  :label="agent.nickname"
                  :value="agent.id"
                ></el-option>
              </el-select>
            </div>
          </div>
        </div>
      </el-form>


      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog = false">取消</el-button>
        <el-button type="primary" @click="submitDialog" :loading="dialogLoading">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="costDialog"
      title="成本分摊"
    >
      <el-table
        border
        :data="costDialogData.shipmentCostList"
      >
        <el-table-column
          prop="shipmentNo"
          label="货件单号"
          align="center"
          min-width="150"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          v-for="item in shipmentAgentList"
          :key="item.id"
          :prop="'costValueAgentId' + item.id"
          :label="item.nickname"
          align="center"
          min-width="100"
        >
          <template v-slot="{row}">
            <template v-if="row['costValueAgentId' + item.id] !== undefined">
              {{row['costValueAgentId' + item.id]}}
            </template>
            <template v-else>
              -
            </template>
          </template>
        </el-table-column>
        <el-table-column
          prop="sumCostValue"
          label="成本合计"
          align="center"
          min-width="100"
        ></el-table-column>

      </el-table>
    </el-dialog>
  </div>

</template>

<script>
import {formatDate} from "@/utils/common";
import request from "@/utils/request";
import AllCostMixin from "@/views/FLData/mixin/AllCostMixin";
import {deepCopy} from "@/utils";

export default {
  name: "ContainerDataTable",
  mixins: [AllCostMixin],
  props: {
    tableData: {
      default: () => [],
      type: Array,
    },
    apiTimes: {
      default: 0,
      type: Number,
    },
    agentList: {
      default: () => [],
      type: Array,
    }
  },
  computed: {
    shipmentAgentList(){
      const shipmentCostList = this.costDialogData.shipmentCostList
      const agentIds = []
      shipmentCostList.forEach(item => {
        for (const key in item) {
          const keyword = 'costValueAgentId'
          // 包含keyword的键
          if(key.includes(keyword)){
            let agentId = key.replace(keyword, '')
            agentIds.push(Number(agentId))
          }
        }
      })
      return this.agentList.filter(item => agentIds.includes(item.id));
    }
  },
  updated () {
    this.$nextTick(() => {
      this.$refs['tableData']?.doLayout();
    })
  },
  data(){
    return {
      timeFormat: 'yyyy-MM-dd',
      dialog: false,
      dialogLoading: false,
      dialogForm: {
        containerId: '',
        transferTypeType: '', // 空运/海运
        seaCostList: [], // 海运成本
        airCostList: [], // 空运成本
        HWCCostList: [], // 海外仓成本
      },
      rules: {
        feeValue: [
          {required: true, message: '请填写应收合计', trigger: 'blur'},
        ],
      },
      costDialog: false,
      costDialogData: {
        id: 0,
        shipmentCostList: [],
      }
    }
  },
  methods: {
    formatDate,
    showDialog(row){
      this.dialogForm.containerId = row.id
      this.dialogForm.transferTypeType = row.transferTypeType
      this.dialogForm.seaCostList = [];
      this.dialogForm.airCostList = [];
      this.dialogForm.HWCCostList = [];
      if(this.dialogForm.transferTypeType === 'sea'){
        // 海运
        this.dialogForm.seaCostList = this.seaCostList.map(item=>{
          let agentId = item.agentList[0].id
          let costValue = 0
          row.containerCostList.some(costItem => {
            if(costItem.costId === item.id && costItem.costType === 'sea'){
              agentId = costItem.agentId
              costValue = costItem.costValue
              return true
            }
          })
          const obj = {
            id: item.id,
            costName: item.costName,
            costValue: costValue,
            agentId: agentId,
            agentList: item.agentList,
          }
          return obj
        })
      }else if(this.dialogForm.transferTypeType === 'air'){
        // 空运
        this.dialogForm.airCostList = this.airCostList.map(item=>{
          let agentId = item.agentList[0].id
          let costValue = 0
          row.containerCostList.some(costItem => {
            if(costItem.costId === item.id && costItem.costType === 'air'){
              agentId = costItem.agentId
              costValue = costItem.costValue
              return true
            }
          })
          const obj = {
            id: item.id,
            costName: item.costName,
            costValue: costValue,
            agentId: agentId,
            agentList: item.agentList,
          }
          return obj
        })
      }
      // 海外仓
      this.dialogForm.HWCCostList = this.HWCCostList.map(item=>{
        let agentId = item.agentList[0].id
        let costValue = 0
        row.containerCostList.some(costItem => {
          if(costItem.costId === item.id && costItem.costType === 'HWC'){
            agentId = costItem.agentId
            costValue = costItem.costValue
            return true
          }
        })
        const obj = {
          id: item.id,
          costName: item.costName,
          costValue: costValue,
          agentId: agentId,
          agentList: item.agentList,
        }
        return obj
      })

      this.dialog = true
    },
    submitDialog(){
      this.$refs.dialogForm.validate(valid=>{
        if(valid){
          const data = {
            containerId: this.dialogForm.containerId,
            seaCostList: [],
            airCostList: [],
            HWCCostList: [],
          }
          const listKey = ['seaCostList', 'airCostList', 'HWCCostList']
          for (const listKeyKey of listKey) {
            data[listKeyKey] = this.dialogForm[listKeyKey].map(item=>{
              return {
                costId: item.id,
                costValue: item.costValue,
                agentId: item.agentId,
              }
            })
          }

          this.dialogLoading = true
          request({
            url: '/finance/saveContainerCost',
            method: 'post',
            handleError: true,
            data: data
          })
            .then(res=>{
              this.dialogLoading = false
              if(res.error === 0){
                this.$sMsg(res.message)
                this.dialog = false
                this.$emit('changeData')
              }else{
                this.$eMsg(res.message)
              }
            })
        }
      })
    },
    showCostDialog(row){
      this.costDialogData = deepCopy(row)
      this.costDialog = true
    }
  },
}
</script>


<style scoped lang="scss">
.cost-box{
  .cost-title{
    font-size: 16px;
    color: #1890ff;
    font-weight: 500;
    margin-bottom: 20px;
  }
  .cost-item{
    display: flex;
    font-size: 14px;
    justify-content: flex-start;
    margin-bottom: 10px;
    align-items: center;
    .cost-label{
      min-width: 100px;
    }
    .cost-value{
      min-width: 200px;
    }
    .cost-agent{
      min-width: 200px;
    }
  }
  .cost-header{
    color: #AAAAAA;
  }
}
</style>
